package groupd

import (
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

// WrapIa2Gid 将infod.InfoAggregate 转换为GroupInfoDesc
func WrapIa2Gid(ctx ddd.Context, g *GroupAggregate, i *infod.InfoAggregate, car columnd.ColumnAggregateRoot) GroupInfoDesc {
	weight := 0
	if g.InfoWeight == 0 {
		weight = i.Weight
	}
	cname := ""
	col, err := car.GetColumn(ctx, i.ColumnID)
	if err != nil {
		log.Warnf("获取栏目(%v)信息失败：%v", i.ColumnID, err)
	} else {
		cname = col.Name
	}
	title := i.Title
	if i.Kind == infod.KindSimplify {
		title = i.Content
	}
	return GroupInfoDesc{
		GroupID:     g.GroupID,
		InfoID:      i.InfoID,
		Weight:      weight,
		Title:       title,
		ColumnID:    i.ColumnID,
		ColumnName:  cname,
		PublishTime: i.PublishTime,
	}
}

// RefreshGroupInfo 异步刷新组内信息
func RefreshGroupInfo(ga *GroupAggregate, iar infod.InfoAggregateRoot, car columnd.ColumnAggregateRoot) {
	go ddd.ExecContextForRepo(func(ctx ddd.Context) {
		is := infod.InfoSearch{
			Status: []infod.IStatus{infod.IStatusPublished},
		}

		gis := make([]GroupInfoDesc, 0, 100)
		if err := infod.WalkInfos(ctx, iar, is, 0, func(i *infod.InfoAggregate) {
			ic := NewInfoColl(i)
			if ga.MatchGroupInfo(ic) {
				gis = append(gis, WrapIa2Gid(ctx, ga, i, car))
			}
			if len(gis) >= 100 {
				if err := ga.AppendInfos(ctx, gis); err != nil {
					log.Warnf("1)向信息组(%v)追加信息失败%+v", ga.GroupID, err)
					return
				}
				gis = make([]GroupInfoDesc, 0, 100)
			}
		}); err != nil {
			log.Warnf("2)向信息组(%v)追加信息失败%+v", ga.GroupID, err)
			return
		}
		if len(gis) > 0 {
			if err := ga.AppendInfos(ctx, gis); err != nil {
				log.Warnf("3)向信息组(%v)追加信息失败%+v", ga.GroupID, err)
				return
			}
		}
	})

}
